<!--
 * @Descripttion: 
 * @Author: jhw
 * @Date: 2023-10-25 11:40:20
 * @LastEditors: jhw
 * @LastEditTime: 2024-07-15 09:45:49
-->
<template>
  <h1>上传文件</h1>
  <el-upload
    v-model:file-list="fileList"
    class="upload-demo"
    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    list-type="picture"
  >
    <el-button type="primary">Click to upload</el-button>
    <template #tip>
      <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
    </template>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref } from 'vue';

import type { UploadProps, UploadUserFile } from 'element-plus';

const fileList = ref<UploadUserFile[]>([
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'food2.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
]);

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePreview: UploadProps['onPreview'] = (file) => {
  console.log(file);
};
</script>

<!-- <template>
  <div>
    <h1>上传视频</h1>
    <input type="file" @change="onFileChange" accept="video/*" />
    <button @click="uploadVideo" :disabled="!selectedFile">上传</button>
    <p v-if="uploadProgress > 0">上传进度：{{ uploadProgress }}%</p>
    <p v-if="uploadStatus">{{ uploadStatus }}</p>
  </div>
</template>

<script>
import { ref } from 'vue';
import axios from 'axios';

export default {
  setup() {
    const selectedFile = ref(null);
    const uploadProgress = ref(0);
    const uploadStatus = ref('');

    const onFileChange = (event) => {
      selectedFile.value = event.target.files[0];
    };

    const uploadVideo = async () => {
      if (!selectedFile.value) {
        uploadStatus.value = '请选择一个视频文件';
        return;
      }

      const formData = new FormData();
      formData.append('video', selectedFile.value);

      try {
        const response = await axios.post('/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          onUploadProgress: (progressEvent) => {
            uploadProgress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          },
        });

        uploadStatus.value = '上传成功';
        console.log(response.data);
      } catch (error) {
        uploadStatus.value = '上传失败';
        console.error(error);
      }
    };

    return {
      selectedFile,
      uploadProgress,
      uploadStatus,
      onFileChange,
      uploadVideo,
    };
  },
};
</script>

<style scoped>
/* 样式可以根据需要自定义 */
</style> -->
